package com.audaque.springboot.foshanupload.web.datamongodbdemo.service.impl;


import com.audaque.springboot.foshanupload.web.datamongodbmodeldemo.model.pojo.Cat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yangshuo
 * @date 2018/12/4 16:18
 */
@Service
public class CatOperations {

    @Autowired
    private MongoOperations mongoOperations;

    /**
     * 向mongodb中插入一条数据
     */
    public void insert(Cat cat) {
        mongoOperations.insert(cat);
    }

    /**
     * 批量插入
     */
    public void batchInsert(List<Cat> catList) {
        mongoOperations.insertAll(catList);
    }

    /**
     * 根据名字查询
     */
    public List<Cat> queryByName(String name) {
        Criteria criteria = Criteria.where("name").is(name);
        Query query = new Query(criteria);
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 组合条件查询
     */
    public List<Cat> queryByNameAndAge(String name, int age) {
        Criteria criteria = Criteria.where("name").is(name);
        criteria.and("age").is(1);
        Query query = new Query(criteria);
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 根据list里的数据查询
     */
    public List<Cat> queryByHobbyList(List<String> hobbyList) {
        Criteria criteria = Criteria.where("hobbyList").in(hobbyList);
        Query query = new Query(criteria);
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 根据时间排序
     */
    public List<Cat> orderByCreateTime() {
        Query query = new Query().with( Sort.by(Sort.Direction.DESC, "createTime"));
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 根据年龄区间查询
     */
    public List<Cat> queryByAgeRange(int min, int max) {
        Criteria criteria = Criteria.where("age").gte(min).lte(max);
        Query query = new Query(criteria);
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 其余的条件删除与更新都是先拼好Query与查询类型
     * 只是换了最后调用的函数，这里不再演示
     */
    public void deleteAll() {
        mongoOperations.dropCollection(Cat.class);
    }
}
